import requests
import time

def seweb_login(login_url, login_data):
    access_token = None
    try:
        response = requests.post(login_url, json=login_data)
        token = response.json()['data']['access']
        access_token = {'Authorization': f"JWT {token}"}
        return access_token
    except Exception as e:
        message = "Failed login seweb:" + str(e)
        return message

def seweb_logout(logout_url, token):
    try:
        response = requests.post(logout_url, headers=token)
        message = response.json()['msg']
        return message
    except Exception as e:
        message = "Failed logout from seweb:" + str(e)
        return message
    
def cmdb_get_vm(url, token):
    cmdb_server = []
    try:
        cmdb_get_url = url + '?limit=999'
        response = requests.get(cmdb_get_url, headers=token)
        server_all = response.json()['data']
        for vm in server_all:
            id = vm['id']
            vmid = vm['vmid']
            vmhost = vm['vmhost']
            cmdb_server.append({'id': id, 'vmid': vmid, 'vmhost': vmhost})
        return cmdb_server
    except Exception as e:
        message = "Failed to get cmdb vmserver data:" + str(e)
        return message
    
def cmdb_get_physerver(url, token):
    cmdb_server = []
    try:
        cmdb_get_url = url + '?limit=999'
        response = requests.get(cmdb_get_url, headers=token)
        server_all = response.json()['data']
        for physerver in server_all:
            id = physerver['id']
            name = physerver['name']
            hostname = physerver['hostname']
            sn = physerver['sn']
            ipaddress = physerver['ipaddress']
            cmdb_server.append({'id': id, 'name': name, 'hostname': hostname, 'sn': sn, 'ipaddress': ipaddress})
        return cmdb_server
    except Exception as e:
        message = "Failed to get cmdb physerver data:" + str(e)
        return message
    
def cmdb_vm_create_or_update(local_data, cmdb_data, url, token, log_path):
    vms = []
    for item in local_data:
        vm_id = None
        if cmdb_data:
            for server in cmdb_data:
                if item['vmid'] == server['vmid']:
                    vm_id = str(server['id'])
                    break
        vms.append((item, vm_id))

    for vm , id in vms:
        if id is not None:
            try:
                update_url = url + id + '/'
                response = requests.put(update_url, headers=token, json=vm)
            except Exception as e:
                message = 'Failed to update: ' + vm['name'] + ' ' + str(e)
                with open(log_path, 'ab') as f:
                    log = 'Time:%s \t API:%s \t Result:%s \n' % (time.strftime('%Y-%m-%d %H:%M:%S'),url, message)
                    f.write(log.encode())
        else:
            try:
                create_url = url
                response = requests.post(create_url, headers=token, json=vm)
            except Exception as e:
                message = 'Failed to create vm:' + vm['name'] + ' ' + str(e)
                with open(log_path, 'ab') as f:
                    log = 'Time:%s \t API:%s \t Result:%s \n' % (time.strftime('%Y-%m-%d %H:%M:%S'),url, message)
                    f.write(log.encode())

def cmdb_physerver_create_or_update(phy_servers, url, token, log_path):
    for server , id in phy_servers:
        if id and server['name']:
            try:
                update_url = url + id + '/'
                response = requests.put(update_url, headers=token, json=server)
            except Exception as e:
                message = 'Failed to update: ' + server['hostname'] + ' ' + str(e)
                with open(log_path, 'ab') as f:
                    log = 'Time:%s \t API:%s \t Result:%s \n' % (time.strftime('%Y-%m-%d %H:%M:%S'),url, message)
                    f.write(log.encode())
        else:
            model = server['model']
            sn = server['sn']
            first_space_index = model.find(' ')
            if first_space_index != -1:
                # 取第一个空格后的所有内容
                substring = model[first_space_index+1:]
                # 将剩余部分转换为大写并去除空格
                sub_name = ''.join(substring.upper().split())
                name = f"{sub_name}-{sn}"
            else:
                # 如果没有空格则直接转换为大写
                sub_name = model.upper()
                name = f"{sub_name}-{sn}"
            server['name'] = name

            try:
                create_url = url
                response = requests.post(create_url, headers=token, json=server)
            except Exception as e:
                message = 'Failed to create server:' + server['hostname'] + ' ' + str(e)
                with open(log_path, 'ab') as f:
                    log = 'Time:%s \t API:%s \t Result:%s \n' % (time.strftime('%Y-%m-%d %H:%M:%S'),url, message)
                    f.write(log.encode())





